public class Solution {
    private int n;
    private int[][] connected;
    private boolean[] visited;

    private void dfs(int u) {
        visited[u] = true;
        for (int v = 0; v < n; v++) {
            if (connected[u][v] == 1 && u != v && !visited[v]) {
                dfs(v);
            }
        }
    }

    public int findCircleNum(int[][] isConnected) {
        this.n = isConnected.length;
        this.connected = isConnected;
        this.visited = new boolean[n];
        int cnt = 0;
        for (int i = 0; i < n; i++) {
            if (!visited[i]) {
                dfs(i);
                cnt++;
            }
        }
        return cnt;
    }
}